package com.rf.richfitwheel.admin.sys.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.*;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.MapCaseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rf.richfitwheel.common.contants.Constant;

/**
 * 系统用户
 *
 * @author hushouquan
 * @date 2018-11-25
 */
@Service("sysUserAuthService")
public class SysUserAuthServiceImpl implements SysUserAuthService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao

    @Autowired
    private OrgService orgService;

    @Autowired
    private SysUserMngOrgService sysUserMngOrgService;

    @Autowired
    private SysUserAuthDataService sysUserAuthDataService;

    @Autowired
    private SysUserStationService sysUserStationService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 根据User获取数据
     *
     * @param user
     * @return List<User>
     */
    @Override
    public List<User> getUser(User user) throws Exception {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (user.getUsername() != null && !user.getUsername().equals("")) {
            criteria.andUsernameEqualTo(user.getUsername());
        }
        if (user.getId() != null && !"".equals(user.getId())) {
            criteria.andIdEqualTo(user.getId());
        }
        if (user.getAccountName() != null && !"".equals(user.getAccountName())) {
            criteria.andAccountNameEqualTo(user.getAccountName());
        }
        if (user.getStatus() != null && !"".equals(user.getStatus())) {
            criteria.andStatusIn(Arrays.asList(user.getStatus().split(",")));
        }
        if (user.getOrgId() != null && !"".equals(user.getOrgId())) {
            criteria.andOrgIdEqualTo(user.getOrgId());
        }
        if (user.getIdType() != null && !"".equals(user.getIdType())) {
            criteria.andIdTypeEqualTo(user.getIdType());
        }
        if (user.getIdNo() != null && !"".equals(user.getIdNo())) {
            criteria.andIdNoEqualTo(user.getIdNo());
        }
        if (user.getTenantId() != null && !"".equals(user.getTenantId())) {
            criteria.andTenantIdEqualTo(user.getTenantId());
        }
        example.setOrderByClause(" order_num ");
        List<User> list = userMapper.selectByExample(example);
        return list;
    }

    @Override
    public Org getOrg(String orgId) {
        return orgMapper.selectByPrimaryKey(orgId);
    }

    /**
     * 修改用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 根据用户id查询用户资源权限
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> getResourcesByUserId(String id) {
        List<Map<String, Object>> list = MapCaseUtil.mapKeyToLowerCase(userMapper.getResourcesByUserId(id));
        return list;
    }


    @Override
    public UserVO getUserVoByUsername(String username) {
        UserVO userVO = new UserVO();
        User user = this.getUserByUsername(username);
        BeanUtils.copyProperties(user, userVO);
        OrgVO org = orgService.getOrgAndParentOrgByOrgId(user.getOrgId());//获取用户所属部门
        userVO.setOrg(org);
        List<OrgVO> mngOrgs = new ArrayList<>();//用户管辖部门列表
        //获取所有管辖部门
        List<UserMngOrg> userMngOrgs = sysUserMngOrgService.getListByUserId(userVO.getId());//获取用户管辖部门列表
        for (UserMngOrg userMngOrg : userMngOrgs) {
            OrgVO orgVO = orgService.getOrgAndParentOrgByOrgId(userMngOrg.getOrgId());
            orgVO.setDefaultState(userMngOrg.getDefaultState());//设置默认管辖部门状态
            if (userMngOrg.getDefaultState().equals("1")) {//设置默认管辖部门,1是默认管辖部门
                Map<String, String> dataLevels = sysUserAuthDataService.getAuthDataByUserIdAndOrgId(userVO.getId(), orgVO.getId());
                orgVO.setDataLevels(dataLevels);
                userVO.setDefaultOrg(orgVO);
                /*userVO.setDefaultDeptId(orgVO.getId());
                userVO.setDefaultDeptCode(orgVO.getOrgCode());
                userVO.setDefaultDeptName(orgVO.getOrgName());
                if(Constant.OrgRank.ORGRANK_COMPANY.getValue().equals(orgVO.getOrgRank())){
                    userVO.setDefaultOrgId(orgVO.getId());
                    userVO.setDefaultOrgCode(orgVO.getOrgCode());
                    userVO.setDefaultOrgName(orgVO.getOrgName());
                }else {
                    userVO.setDefaultOrgId(orgVO.getParentOrg() == null ? null : orgVO.getParentOrg().getId());
                    userVO.setDefaultOrgCode(orgVO.getParentOrg() == null ? null : orgVO.getParentOrg().getOrgCode());
                    userVO.setDefaultOrgName(orgVO.getParentOrg() == null ? null : orgVO.getParentOrg().getOrgName());
                }*/
                if(Constant.OrgRank.ORGRANK_DEPT.getValue().equals(orgVO.getOrgRank())){
                    userVO.setDefaultDeptId(orgVO.getId());
                    userVO.setDefaultDeptCode(orgVO.getOrgCode());
                    userVO.setDefaultDeptName(orgVO.getOrgName());
                    userVO.setDefaultOrgId(null);
                    userVO.setDefaultOrgCode(null);
                    userVO.setDefaultOrgName(null);
                }else{
                    userVO.setDefaultDeptId(null);
                    userVO.setDefaultDeptCode(null);
                    userVO.setDefaultDeptName(null);
                    userVO.setDefaultOrgId(orgVO.getId());
                    userVO.setDefaultOrgCode(orgVO.getOrgCode());
                    userVO.setDefaultOrgName(orgVO.getOrgName());
                }
            }
            //管辖部门对应模块的数据权限,key是模块，value是数据权限
            Map<String, String> dataLevels = sysUserAuthDataService.getAuthDataByUserIdAndOrgId(userVO.getId(), orgVO.getId());
            orgVO.setDataLevels(dataLevels);
            mngOrgs.add(orgVO);
        }
        userVO.setMngOrgs(mngOrgs);
        List<String> stationIds = sysUserStationService.getStationIdsByUserId(userVO.getId());
        List<String> roles = sysUserRoleService.getListByUserId(userVO.getId())
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
        userVO.setStationIds(stationIds);
        userVO.setRoles(roles);
        return userVO;
    }

    private User getUserByUsername(String username) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        //example.setOrderByClause(" ordernum ");
        List<User> users = userMapper.selectByExample(example);
        if (users.size() > 0) {
            return users.get(0);
        }
        return null;
    }


}
